<template>
  <div class="settings-item app-variable">
    <div class="header">
      <div class="title">
        全局变量
        <Tooltip
          transfer
          theme="light"
          placement="bottom"
          max-width="400"
          content="提示"
        >
          <Icon type="ios-help-circle-outline" />
        </Tooltip>
      </div>
      <div class="actions">
        <text-button type="normal" icon="md-add" @click="visible = true"
          >新增</text-button
        >
      </div>
    </div>
    <div class="content">
      <el-table :data="form.globalvarList" style="width: 100%">
        <el-table-column label="变量名" prop="varname" >
        </el-table-column>
        <el-table-column label="必填" prop="isrequired">
          <template #default="{ row }">
            <Icon v-if="row.isrequired" size="20" type="md-checkmark" />
            <span v-else></span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="{$index, row}">
            <Icon
              class="action-btn"
              size="20"
              type="md-settings"
              @click.stop="handleEditSelect($index, row)"
            ></Icon>
            <Icon
              class="action-btn"
              size="20"
              type="ios-trash"
              @click.stop="handleRemoveSelect($index)"
            ></Icon>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
  <CommonDialog
    title="变量设置"
    v-model="visible"
    :confirmLoading="loading"
    width="800px"
    @cancel="cancel"
  >
    <div class="flex-box">
      <div class="select-box">
        <div class="title">变量类型</div>
        <div class="select-list">
          <div
            class="select-item"
            v-for="(item, i) in DEFAULT_TYPE"
            :class="{ active: typeIndex == item.id }"
            :key="item.id"
            @click="handleTypeSelect(i, item)"
          >
            {{ item.name }}
          </div>
        </div>
      </div>
      <div class="form-box">
        <Form
          ref="formEl"
          :model="formData"
          :rules="rules"
          label-position="left"
          :label-width="100"
        >
          <FormItem label="变量名" prop="varname">
            <Input
              v-model="formData.varname"
              placeholder="请输入变量名"
              clearable
            ></Input>
          </FormItem>
          <FormItem label="变量描述" prop="vardesc">
            <Input
              v-model="formData.vardesc"
              type="textarea"
              placeholder="描述该输入字段的功能，如果为工具调用参数，则该描述会影响模型生成的质量"
              clearable
            ></Input>
          </FormItem>
          <FormItem label="数据类型" v-show="typeIndex != 'custom'">
            {{ formData.datatype }}
          </FormItem>
          <FormItem label="数据类型" v-show="typeIndex == 'custom'">
            <Select v-model="formData.datatype">
              <Option v-for="item in TYPE_OPTIONS" :value="item" :key="item">{{
                item
              }}</Option>
            </Select>
          </FormItem>
          <FormItem label="必填" prop="isrequired"  v-show="typeIndex != 'custom'">
            <Switch v-model="formData.isrequired" />
          </FormItem>
          <FormItem label="最大长度" prop="maxlength" v-show="typeIndex == 'text'">
            <InputNumber
              v-model="formData.maxlength"
              placeholder=""
              clearable
            ></InputNumber>
          </FormItem>
          <FormItem label="最大值" prop="maxval" v-show="typeIndex == 'num'">
            <InputNumber v-model="formData.maxval" clearable></InputNumber>
          </FormItem>
          <FormItem label="最小值" prop="minval" v-show="typeIndex == 'num'">
            <InputNumber v-model="formData.minval" clearable></InputNumber>
          </FormItem>
          <FormItem label="默认值" prop="defaultvalue">
            <Input
              v-model="formData.defaultvalue"
              type="textarea"
              placeholder=""
              clearable
              v-show="typeIndex == 'text' || typeIndex == 'custom'"
            ></Input>
            <InputNumber
              v-model="formData.defaultvalue"
              placeholder=""
              clearable
              v-show="typeIndex == 'num'"
            ></InputNumber>
            <Select v-model="formData.defaultvalue" v-show="typeIndex == 'radio'">
              <Option
                v-for="item in formData.options"
                :value="item.opvalue"
                :key="item.opvalue"
                >{{ item.opvalue }}</Option
              >
            </Select>
          </FormItem>
          <FormItem
            v-for="(select, i) in formData.options"
            :label="'选项' + (i + 1)"
            :prop="'options.' + i + '.opvalue'"
            v-show="typeIndex == 'radio'"
          >
            <div style="display: flex">
              <Input
                v-model="select.opvalue"
                :placeholder="'选项' + (i + 1)"
                clearable
              ></Input>
              <Icon
                type="ios-trash"
                size="22"
                style="margin-left: 20px; cursor: pointer"
                @click="removeSelect(i)"
                v-if="formData.options.length > 1"
              />
            </div>
          </FormItem>
          <Button icon="md-add" type="plain" @click="addSelect" v-show="typeIndex == 'radio'"
            >添加选项</Button
          >
        </Form>
      </div>
    </div>

    <template #footer>
      <Button @click="cancel">关闭</Button>
      <Button type="primary" ghost @click="handleSelect(true)">确认</Button>
      <Button type="primary" @click="handleSelect(false)" v-show="editIndex==undefined">继续添加</Button>
    </template>
  </CommonDialog>
</template>
<script setup>
import { ref } from 'vue';
import CommonDialog from '@/components/CommonDialog/index.vue';
import { Message } from 'view-ui-plus';

const props = defineProps({
  form: {
    type: Object,
    default: () => {}
  }
})
// 弹窗显示
const visible = ref(false);
const loading = ref(false);

const DEFAULT_TYPE = [
  {
    name: '文本输入框',
    id: 'text',
    type: 'String',
  },
  {
    name: '数字输入框',
    id: 'num',
    type: 'Number',
  },
  {
    name: '单选框',
    id: 'radio',
    type: 'String',
  },
  {
    name: '自定义变量',
    id: 'custom',
    type: 'String',
  },
];

const TYPE_OPTIONS = [
  'String',
  'Number',
  'Boolean',
  'Object',
  'Array<string>',
  'Array<number>',
  'Array<boolean>',
  'Array<object>',
  'Any',
  '历史记录',
  '知识库引用',
  '选择知识库',
  '动态输入',
];
const editIndex = ref(undefined);
const formEl = ref(null);
const formData = ref({
  globaltype: 'text',
  varname: '',
  vardesc: '',
  datatype: 'String',
  isrequired: true,
  maxlength: undefined,
  defaultvalue: undefined,
  maxval: undefined,
  minval: undefined,
  options: undefined,
});

const typeIndex = ref('text');
const handleTypeSelect = (i, item) => {
  if (typeIndex.value != item.id) {
    typeIndex.value = item.id;
    formData.value.datatype = item.type;
    formData.value.globaltype = item.id;
  }
  if (i == 2) {
    formData.value.options = [
      {
        opvalue: '',
        opname: '选项1',
      },
    ];
  }
};

const addSelect = () => {
  formData.value.options.push({
    opvalue: '',
    opname: '选项' + formData.value.options.length,
  });
};
const removeSelect = (i) => {
  formData.value.options.splice(i, 1);
};

const handleSelect = (hide = true) => {
  console.log(editIndex.value == undefined)
  const temp = JSON.parse(JSON.stringify(formData.value))
  if (editIndex.value == undefined) {
    props.form.globalvarList.push({...temp});
    Message.success('添加成功');
  } else {
    props.form.globalvarList[editIndex.value] = {...temp};
    Message.success('编辑成功');
  }
  visible.value = !hide;
  editIndex.value = undefined;
  typeIndex.value =  'text';
  formEl.value?.resetFields();
}

const cancel = () => {
  formEl.value?.resetFields();
  visible.value = false;
}

// 编辑已选择的变量
const handleEditSelect = (index, row) => {
  const temp = JSON.parse(JSON.stringify(row))

  editIndex.value = index;
  formData.value = {...temp};
  typeIndex.value =  row.globaltype;
  visible.value = true;
}
// 移除已选择的变量
const handleRemoveSelect = (index) => {
  props.form.globalvarList.splice(index, 1)
}

</script>
<style lang="scss" scoped>
.flex-box {
  display: flex;
}
.select-box {
  width: 40%;
  padding: 10px;
}
.form-box {
  width: 60%;
  height: 450px;
  padding: 10px;
  overflow-y: auto;
  border-left: 1px solid #e2e8f0;
}

.select-list {
  display: flex;
  flex-wrap: wrap;
  margin-top: 20px;
}
.select-item {
  width: calc(50% - 10px);
  padding: 10px;
  margin-right: 10px;
  margin-bottom: 10px;
  border-radius: 8px;
  border: 1px solid;
  border-color: rgb(232, 235, 240);
  background-color: rgb(251, 251, 252);
  transition: all 0.2s ease-in-out;
  cursor: pointer;
  &:hover {
    border-color: #5e8fff;
  }
  &.active {
    border-color: #5e8fff;
    background-color: #e1eaff;
  }
}
.action-btn {
  margin-left: 10px;
  cursor: pointer;
}
</style>
